package com.liuwa.social.weixin.push;

import com.liuwa.social.weixin.utils.WeixinUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.liuwa.social.http.WeixinHttpClient;
import com.liuwa.social.weixin.vo.AccessToken;


/**
 * 模板推送
 * @author Rubekid
 *
 * 2017年3月31日 下午8:26:15
 */
public class TemplatePusher {

	private static final String PUSH_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
	
	private static final Logger LOGGER = LoggerFactory.getLogger(TemplatePusher.class);


	public static void send(Template template, String appId, String appSecret){
		try {
			AccessToken accessToken = WeixinUtils.getAccessToken(appId, appSecret);
			String url = String.format(PUSH_URL, accessToken.getAccessToken());
			String content = WeixinHttpClient.post(url, (JSONObject) (JSONObject.toJSON(template)));
			if(content.startsWith("{") && content.endsWith("}")) {
				JSONObject response = JSONObject.parseObject(content);
				if(response.getInteger("errcode") != 0) {
					LOGGER.error(content);
				}
			}
			
		} catch (RuntimeException ex) {
			LOGGER.error(ex.getMessage(), ex);
		}
	}
}
